package cool.xiaokang.familyaccount.controller;

import java.io.IOException;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.alibaba.fastjson.serializer.PropertyFilter;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cool.xiaokang.familyaccount.pojo.Manager;
import cool.xiaokang.familyaccount.service.InAccountService;
import cool.xiaokang.familyaccount.service.InvestService;
import cool.xiaokang.familyaccount.service.LoanService;
import cool.xiaokang.familyaccount.service.ManagerService;
import cool.xiaokang.familyaccount.service.OutAccountService;
import cool.xiaokang.familyaccount.utils.CryptographyUtil;
import cool.xiaokang.familyaccount.utils.PageBean;
import cool.xiaokang.familyaccount.utils.ResponseUtils;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Controller
@Scope("prototype")
public class ManagerAction extends ActionSupport implements ModelDriven<Manager> {
	private static final long serialVersionUID = -1508072104076758680L;
	private static final Logger LOGGER = Logger.getRootLogger();
	@Autowired
	private ManagerService managerService;

	@Autowired
	private InAccountService inAccountService;

	@Autowired
	private OutAccountService outAccountService;

	@Autowired
	private InvestService investService;

	@Autowired
	private LoanService loanService;

	private Manager manager = new Manager();
	private String checkcode;
	private String[] roleIds;
	private Integer page;
	private Integer rows;

	public String login() {
		Map<String, Object> map = ActionContext.getContext().getSession();
		// 获取session中的验证码
		String validatecode = (String) map.get("key");
		// 判断输入的验证码和用户名
		if (StringUtils.isNotBlank(checkcode) && checkcode.equalsIgnoreCase(validatecode)
				&& StringUtils.isNotBlank(manager.getManager_name())) {
			Subject subject = SecurityUtils.getSubject();
			// 输入多的用户名和密码比对shiro框架中动态查询的的用户名和密码
			String cryptographyPwd = CryptographyUtil.md5(manager.getManager_pwd(),
					CryptographyUtil.md5(CryptographyUtil.FAMILY, "familyaccount"));
			AuthenticationToken token = new UsernamePasswordToken(manager.getManager_name(), cryptographyPwd);
			try {
				// 认证通过
				subject.login(token);
				Manager currentManager = (Manager) subject.getPrincipal();
				ActionContext.getContext().getSession().put("currentManager", currentManager);
				return "home";
			} catch (Exception e) {
				e.printStackTrace();
				this.addActionError("认证失败，请检查输入！");
				return "toLogin";
			}
		} else {
			this.addActionError("输入的验证码有误！");
			return "toLogin";
		}
	}

	// 修改密码
	public String editPwd() {
		Manager model = (Manager) ActionContext.getContext().getSession().get("currentManager");
		managerService.editpwd(manager.getManager_pwd(), model.getManager_id());
		ActionContext.getContext().getSession().remove("currentManager");
		return "logout";
	}

	public String logout() {
		ActionContext.getContext().getSession().remove("currentManager");
		return "logout";
	}

	@RequiresPermissions("manager-add")
	public String add() {
		LOGGER.info("【ManagerAction_add】>>>roleIds:" + roleIds);
		managerService.save(manager, roleIds);
		return "list";
	}

	@RequiresPermissions("manager-list")
	public String pageQuery() throws IOException {
		DetachedCriteria dc = DetachedCriteria.forClass(Manager.class);
		PageBean pb = new PageBean();
		pb.setCurrentPage(page);
		pb.setPageSize(rows);
		pb.setDetachedCriteria(dc);
		managerService.pageQuery(pb);
		PropertyFilter filter = new PropertyFilter() {
			@Override
			public boolean apply(Object object, String name, Object value) {
				boolean flag = true;
				if (name.equals("detachedCriteria")) {
					flag = false;
				} else if (name.equals("currentPage")) {
					flag = false;
				} else if (name.equals("pageSize")) {
					flag = false;
				} else if (name.equals("roles")) {
					flag = false;
				}
				return flag;
			}
		};
		ResponseUtils.respPageBean(ServletActionContext.getResponse(), pb, filter);
		return NONE;
	}

	@RequiresPermissions("manager-update")
	public String foredit() {
		Manager model = managerService.findById(manager.getManager_id());
		ActionContext.getContext().put("manager", model);
		return "edit";
	}

	// 数据条目报表统计
	public String reportAll() {
		ActionContext.getContext().put("intotal", inAccountService.getTotal());
		ActionContext.getContext().put("outtotal", outAccountService.getTotal());
		ActionContext.getContext().put("investtotal", investService.getTotal());
		ActionContext.getContext().put("loantotal", loanService.getTotal());
		return "report";
	}

	@RequiresPermissions("manager-update")
	public String update() {
		LOGGER.info("【ManagerAction_update】>>>roleIds:" + roleIds);
		managerService.update(manager, roleIds);
		return "list";
	}

	@Override
	public Manager getModel() {
		return manager;
	}

}
